<?php
/**
 * Created by PhpStorm.
 * User: ZNZG
 * Date: 2022/3/16
 * Time: 16:35
 */

namespace app\common\business;


use app\common\exception\BaseException;

class BaseBis
{
    /**
     * 列表查询
     * @return mixed
     */
    public function index()
    {
        $params = input('param.');
        $pagesize = input('param.pagesize',1);
        unset($params['page'],$params['pagesize']);
        $result = $this->model
            ->withSearch(array_keys($params),$params)
            ->paginate($pagesize)
            ->toArray();

        return $result;
    }

    /**
     * 新增
     * @param string $scene
     * @param array $extra_data
     * @return mixed
     * @throws BaseException
     */
    public function save($scene = 'save',$extra_data = [])
    {
        $data = array_merge(input('post.'),$extra_data);
        if(!$this->validate->scene($scene)->check($data))
        {
            throw new BaseException($this->validate->getError());
        }

        try{
            return $this->model->create($data);
        } catch (\Exception $e){
            throw new BaseException($e->getMessage());
        }
    }

    /**
     * 修改
     * @param $id
     * @param string $scene
     * @return mixed
     * @throws BaseException
     */
    public function update($id,$scene = 'update')
    {
        $this->validate->goCheck($scene);

        try{
            return $this->model->update(input('post.'),['id' => $id]);
        } catch (\Exception $e){
            throw new BaseException(['msg' => $e->getMessage()]);
        }
    }

    /**
     * 删除
     * @param int $id
     * @param string $scene
     * @return mixed
     * @throws BaseException
     */
    public function delete(int $id,$scene = 'delete')
    {
        $this->validate->goCheck($scene);
        try{
            $model = $this->model->find($id);
            if($model){
                return $model->delete();
            }
        } catch (\Exception $e){
            throw new BaseException(['msg' => $e->getMessage()]);
        }

        throw new BaseException(['msg' => '查无记录','code' => 404]);
    }

    /**
     * 获取单条数据
     * @param int $id
     * @return mixed
     * @throws BaseException
     */
    public function read(int $id)
    {
        $result = $this->model->find($id);
        if(!$result)
        {
            throw new BaseException(['code' => 404, 'msg' => '查无记录']);
        }

        return $result;
    }
}